<template>
  <div class="delivery-page">
    <div class="toolbar">
      <div class="left">
        <button class="btn primary" @click="showCreate = true">新建</button>
      </div>
      <div class="right">
        <span class="label">关键词</span>
        <input class="input keyword" v-model="query.keyword" placeholder="请输入发货单号" />
        <button class="btn" @click="onSearch">搜索</button>
        <button class="btn" @click="onReset">重置</button>
      </div>
    </div>

    <div class="table-wrapper">
      <table class="table">
        <thead>
          <tr>
            <th style="width:48px"><input type="checkbox" v-model="checkedAll" @change="toggleAll" /></th>
            <th>发货单号</th>
            <th>审批状态</th>
            <th>申请时间</th>
            <th>申请人</th>
            <th>客户</th>
            <th>销售</th>
            <th>发货时间</th>
            <th>发货状态</th>
            <th style="width:100px">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in list" :key="item.id">
            <td><input type="checkbox" v-model="selectedIds" :value="item.id" /></td>
            <td>{{ item.deliveryOrderNo }}</td>
            <td>
              <span :class="['tag', statusClass(item.outboundStatus)]">{{ statusText(item.outboundStatus) }}</span>
            </td>
            <td>{{ item.firstProductName || '-' }}</td>
            <td>{{ item.firstProductSpec || '-' }}</td>
            <td>{{ item.firstProductCategory || '-' }}</td>
            <td>{{ item.firstProductUnit || '-' }}</td>
            <td>{{ item.totalQuantity || '-' }}</td>
            <td>{{ formatDateTime(item.applyTime) }}</td>
            <td><button class="link" @click="view(item)">详情</button></td>
          </tr>
          <tr v-if="!list || list.length === 0">
            <td colspan="10" class="empty">暂无数据</td>
          </tr>
        </tbody>
      </table>
      <div class="table-footer">
        <div class="footer-left">
          <input type="checkbox" v-model="checkedAll" @change="toggleAll" /> 全选
        </div>
        <div class="footer-right">
          <button class="btn" :disabled="page.pageNum===1" @click="changePage(page.pageNum-1)">上一页</button>
          <span>第 {{ page.pageNum }} / {{ totalPages }} 页</span>
          <button class="btn" :disabled="page.pageNum>=totalPages" @click="changePage(page.pageNum+1)">下一页</button>
          <span>{{ page.pageSize }} 条/页</span>
        </div>
      </div>
    </div>

    <div v-if="showCreate" class="modal-mask" @click.self="showCreate=false">
      <div class="modal">
        <h3>新建发货单</h3>
        <div class="form single">
          <label>客户名称</label>
          <input v-model.number="form.customerId" placeholder="请输入客户ID或名称(可留空)" />

          <label>申请人ID</label>
          <input v-model.number="form.uId" placeholder="可留空" />

          <label>关联销售单ID</label>
          <input v-model.number="form.salesId" placeholder="可留空" />

          <label>申请时间</label>
          <input v-model="form.applyTime" type="datetime-local" placeholder="可留空" />

          <label>期望发货时间</label>
          <input v-model="form.expectedDeliveryDate" type="datetime-local" placeholder="可留空" />

          <label>备注</label>
          <input v-model="form.remark" placeholder="可留空" />

          <label>出库状态</label>
          <select v-model.number="form.outboundStatus">
            <option :value="2">未出库</option>
            <option :value="1">部分出库</option>
            <option :value="0">全部出库</option>
          </select>

          <label>审批状态</label>
          <select v-model.number="form.approvalStatus">
            <option :value="1">待审核</option>
            <option :value="0">审核通过</option>
            <option :value="2">审核驳回</option>
          </select>
        </div>
        <div class="actions">
          <button @click="showCreate=false">取消</button>
          <button class="primary" @click="submitCreate">确定</button>
        </div>
      </div>
    </div>

    <div v-if="showDetail" class="drawer-mask" @click.self="showDetail=false">
      <div class="drawer">
        <h3>{{ detail.deliveryOrderNo }} - 发货单详情</h3>
        <div class="detail-sections">
          <div class="section">
            <div class="section-title">基础信息</div>
            <div class="form-grid">
              <div class="form-item">
                <label>发货单号</label>
                <input disabled :value="detail.deliveryOrderNo || '-'" />
              </div>
              <div class="form-item">
                <label>审批状态</label>
                <input disabled :value="renderApprove(detail.approvalStatus)" />
              </div>
              <div class="form-item">
                <label>申请时间</label>
                <input disabled :value="formatDateTime(detail.applyTime)" />
              </div>
              <div class="form-item">
                <label>备注</label>
                <input disabled :value="detail.remark || '-'" />
              </div>
            </div>
          </div>

          <div class="section">
            <div class="section-title">对接人信息</div>
            <div class="form-grid">
              <div class="form-item">
                <label>申请人</label>
                <input disabled :value="detail.uId || '-'" />
              </div>
              <div class="form-item">
                <label>客户</label>
                <input disabled :value="detail.customerId || '-'" />
              </div>
              <div class="form-item">
                <label>关联销售单</label>
                <input disabled :value="detail.salesId || '-'" />
              </div>
              <div class="form-item">
                <label>联系方式</label>
                <input disabled :value="detail.contactPhone || '-'" />
              </div>
            </div>
          </div>

          <div class="section">
            <div class="section-title">发货信息</div>
            <div class="form-grid">
              <div class="form-item">
                <label>期望发货时间</label>
                <input disabled :value="formatDateTime(detail.expectedDeliveryDate)" />
              </div>
              <div class="form-item">
                <label>出库状态</label>
                <input disabled :value="renderOutbound(detail.outboundStatus)" />
              </div>
              <div class="form-item">
                <label>收货地址</label>
                <input disabled :value="detail.address || '-'" />
              </div>
              <div class="form-item">
                <label>邮编</label>
                <input disabled :value="detail.postcode || '-'" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { deliveryPage, deliveryCreate, deliveryDetail } from '@/api/sale/delivery'

export default {
  name: 'DeliveryManagement',
  data() {
    return {
      query: { deliveryOrderNo: '', keyword: '', startTime: '', endTime: '' },
      page: { pageNum: 1, pageSize: 10 },
      list: [],
      total: 0,
      checkedAll: false,
      selectedIds: [],
      showCreate: false,
      form: {
        approvalStatus: 1,
        applyTime: '',
        uId: null,
        customerId: null,
        salesId: null,
        expectedDeliveryDate: '',
        outboundStatus: 2
      },
      showDetail: false,
      detail: {}
    }
  },
  computed: {
    totalPages() {
      return Math.max(1, Math.ceil(this.total / this.page.pageSize))
    }
  },
  created() {
    this.fetch()
  },
  methods: {
    async fetch() {
      const res = await deliveryPage({
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize,
        deliveryOrderNo: this.query.keyword || this.query.deliveryOrderNo || undefined,
        startTime: this.query.startTime || undefined,
        endTime: this.query.endTime || undefined
      })
      const payload = res?.data || res
      const data = payload?.data || payload
      this.list = data?.records || []
      this.total = data?.total || 0
    },
    onSearch() {
      this.page.pageNum = 1
      this.fetch()
    },
    onReset() {
      this.query = { deliveryOrderNo: '', keyword: '', startTime: '', endTime: '' }
      this.page.pageNum = 1
      this.fetch()
    },
    changePage(n) {
      this.page.pageNum = n
      this.fetch()
    },
    toggleAll() {
      if (this.checkedAll) {
        this.selectedIds = (this.list || []).map(i => i.id)
      } else {
        this.selectedIds = []
      }
    },
    statusText(s) {
      if (s === 0) return '已发货'
      if (s === 1) return '部分发货'
      if (s === 2) return '未发货'
      return '-'
    },
    statusClass(s) {
      if (s === 0) return 'tag-green'
      if (s === 1) return 'tag-orange'
      if (s === 2) return 'tag-gray'
      return 'tag-gray'
    },
    renderApprove(s) {
      if (s === 0) return '审核通过'
      if (s === 1) return '待审核'
      if (s === 2) return '审核驳回'
      return '-'
    },
    renderOutbound(s) {
      return this.statusText(s)
    },
    formatDateTime(d) {
      if (!d) return '-'
      const dt = new Date(d)
      const y = dt.getFullYear()
      const m = String(dt.getMonth()+1).padStart(2,'0')
      const da = String(dt.getDate()).padStart(2,'0')
      const hh = String(dt.getHours()).padStart(2,'0')
      const mm = String(dt.getMinutes()).padStart(2,'0')
      return `${y}-${m}-${da} ${hh}:${mm}`
    },
    async submitCreate() {
      const payload = { ...this.form }
      if (payload.applyTime) payload.applyTime = new Date(payload.applyTime)
      if (payload.expectedDeliveryDate) payload.expectedDeliveryDate = new Date(payload.expectedDeliveryDate)
      const res = await deliveryCreate(payload)
      const ok = (res?.data?.code ?? res?.code) === 200
      if (ok) {
        this.showCreate = false
        this.fetch()
      } else {
        alert(res?.data?.message || res?.message || '创建失败')
      }
    },
    async view(item) {
      this.showDetail = true
      const res = await deliveryDetail(item.id)
      const data = res?.data?.data || res?.data || res
      this.detail = data || {}
    }
  }
}
</script>

<style scoped>
.toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
.toolbar .left { display: flex; gap: 8px; }
.toolbar .right { display: flex; align-items: center; gap: 8px; }
.label { color: #666; }
.input { border: 1px solid #dcdfe6; padding: 6px 8px; border-radius: 4px; }
.input.keyword { width: 260px; }
.input.time { width: 180px; }
.btn { border: 1px solid #dcdfe6; background: #fff; padding: 6px 12px; border-radius: 4px; cursor: pointer; }
.btn.primary { background: #409eff; color: #fff; border-color: #409eff; }
.table-wrapper { border: 1px solid #ebeef5; border-radius: 4px; }
.table { width: 100%; border-collapse: collapse; }
.table th, .table td { border-bottom: 1px solid #ebeef5; padding: 10px; text-align: left; }
.table thead th { background: #fafafa; color: #606266; font-weight: 500; }
.link { color: #409eff; background: transparent; border: none; cursor: pointer; }
.empty { text-align: center; color: #909399; padding: 20px; }
.table-footer { display: flex; justify-content: space-between; align-items: center; padding: 10px; }

.tag { padding: 2px 8px; border-radius: 12px; font-size: 12px; }
.tag-green { background: #e8f5e8; color: #4caf50; }
.tag-orange { background: #fff3e0; color: #ff9800; }
.tag-gray { background: #f5f5f5; color: #666; }

.modal-mask { position: fixed; inset: 0; background: rgba(0,0,0,0.4); display: flex; align-items: center; justify-content: center; }
.modal { background: #fff; padding: 16px; width: 460px; border-radius: 6px; }
.form { display: grid; grid-template-columns: 120px 1fr; gap: 8px; }
.form.single { display: grid; grid-template-columns: 100px 1fr; gap: 10px 12px; }
.form.single input, .form.single select { border: 1px solid #dcdfe6; border-radius: 4px; padding: 8px; }
.actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 12px; }
.actions button { border: 1px solid #dcdfe6; background: #fff; padding: 6px 14px; border-radius: 4px; cursor: pointer; }
.actions .primary { background: #409eff; color: #fff; border-color: #409eff; }
.drawer-mask { position: fixed; inset: 0; background: rgba(0,0,0,0.2); display: flex; justify-content: flex-end; }
.drawer { background: #fff; width: 600px; padding: 16px; height: 100%; overflow: auto; }
.detail-sections { display: flex; flex-direction: column; gap: 16px; }
.section { background: #fff; border: 1px solid #ebeef5; border-radius: 6px; }
.section-title { padding: 10px 12px; border-bottom: 1px solid #f0f0f0; font-weight: 600; color: #333; }
.form-grid { padding: 12px; display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px 16px; }
.form-item { display: flex; align-items: center; gap: 10px; }
.form-item label { width: 100px; color: #606266; text-align: right; }
.form-item input { flex: 1; border: 1px solid #dcdfe6; border-radius: 4px; padding: 6px 8px; background: #f9f9f9; }
</style>


